package com.tg.app.helper;

import static android.content.Context.MODE_PRIVATE;
import static com.appbase.custom.BuildConfig.SHOW_AI_SERVICE;
import static com.tg.app.activity.base.DeviceListBaseActivity.OPEN_DRIVE;
import static com.tg.app.activity.base.DeviceListBaseActivity.OPEN_DRIVE_LOCAL;
import static com.tg.app.activity.base.DeviceListBaseActivity.OPEN_SETTING;
import static com.tg.app.activity.base.DeviceListBaseActivity.PUSH_TARGET_LIST;
import static com.tg.app.activity.base.DeviceListBaseActivity.PUSH_TARGET_LIVE;
import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;
import static com.tg.app.activity.device.list.DeviceListPushConfig.FROM_CALL_PAGE_TARGET_LIVE;
import static com.tg.app.activity.device.list.DeviceListPushConfig.OPEN_DRIVE_LOCAL_PALYBACK_SDCARD;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.base.AiSeviceInfo;
import com.appbase.custom.base.CarServerData;
import com.appbase.custom.base.ServiceInfo;
import com.appbase.custom.config.ApiUrl;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.demo.helper.SignalHelper;
import com.demo.view.DeviceCardInfoView;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.backend.service.http.ClientObserver;

import com.tange.module.add.match.DeviceMatchQuery;
import com.tange.module.add.wifi.DeviceWiFiConfiguration;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.log.collection.AppLogManager;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.CloudServiceActivity;
import com.tg.app.activity.base.CameraBaseActivity;
import com.tg.app.activity.device.CameraLiveActivity;
import com.tg.app.activity.device.CameraPipLiveActivity;
import com.tg.app.activity.device.CameraPipPlaybackActivity;
import com.tg.app.activity.device.CameraPlaybackActivity;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.activity.device.add.AddFragmentTabActivity;
import com.tg.app.camera.P2PReport;
import com.tg.app.report.DeviceAddReport;
import com.tg.app.report.DeviceAddReportBean;
import com.tg.app.statistics.TangeVideoPlayStatistics;
import com.tg.app.util.LogUtils;
import com.tg.app.util.UriUtil;
import com.tg.appcommon.android.AbAppUtil;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.sdk.TGErrorCode;
import com.tg.data.bean.DeviceCapAIs;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.helper.DeviceItemHelper;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.http.entity.DeviceMatchBean;
import com.tg.data.http.entity.UserDeviceListBean;
import com.tg.network.socket.http.TGHttp;

import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class DeviceHelper {

    private static final String TAG = "DeviceHelperTAG";

    public static CarServerData getCarServer(DeviceItem deviceItem) {
        return deviceItem != null ? deviceItem.getCarServerData() : null;
    }

    public static boolean isSupportTumble(DeviceItem deviceItem){
        if (deviceItem != null && deviceItem.deviceBasicResp != null && !StringUtils.isEmpty(deviceItem.deviceBasicResp.getAiAbilities())){
            DeviceCapAIs aIs = new DeviceCapAIs(deviceItem.deviceBasicResp.getAiAbilities());
            return aIs.isSupportTumble();
        }
        return false;
    }

    public static boolean isHasCustomerMessage(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.isHasCustomerMessage();
    }

    public static ServiceInfo getServer(DeviceItem deviceItem) {
        return deviceItem != null ? deviceItem.getServer() : null;
    }

    public static boolean hasCarServer(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.getCarServerData() != null;
    }

    public static boolean isBatteryDevice(DeviceItem deviceItem) {
        return deviceItem != null && !isLockBell(deviceItem) && DeviceTypeHelper.isBattery(deviceItem.attrs);

    }


    public static boolean isBirdFeeder(DeviceItem deviceItem){
        return deviceItem != null && DeviceTypeHelper.isBirdFeeder(deviceItem.device_type);
    }

    public static boolean isLpWIFIBirdFeeder(DeviceItem deviceItem){
        return deviceItem != null && DeviceTypeHelper.isLpWIFIBirdFeeder(deviceItem.device_type);
    }

    public static boolean isWIFIBirdFeeder(DeviceItem deviceItem){
        return deviceItem != null && DeviceTypeHelper.isWIFIBirdFeeder(deviceItem.device_type);
    }

    public static boolean isSimBirdFeeder(DeviceItem deviceItem){
        return deviceItem != null && DeviceTypeHelper.isSimBirdFeeder(deviceItem.device_type);
    }


    public static boolean isContains(String attr, String key, String val){
        if (StringUtils.isEmpty(attr)){
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(attr);
        if (jsonObject != null){
            String power = jsonObject.getString(key);
            return StringUtils.equalsIgnoreCase(power, val);
        }
        return false;
    }

    public static boolean isPicLockBell(String attr){
        return isContains(attr, "service", "audio-pic") || isContains(attr, "service", "only-pic");
    }

    public static boolean isIPCDevice(String attr){
        if (StringUtils.isEmpty(attr)){
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(attr);
        if (jsonObject != null){
            String category = jsonObject.getString("category");
            return !StringUtils.isEmpty(category) && category.toLowerCase().contains("ipc");
        }
        return false;
    }

    public static boolean isVideoLockBell(String attr){
        if (StringUtils.isEmpty(attr)){
            return true;
        }
        JSONObject jsonObject = JSONObject.parseObject(attr);
        if (jsonObject != null){
            String service = jsonObject.getString("service");
            if (StringUtils.isEmpty(service)){
                return true;
            }
            return StringUtils.equalsIgnoreCase(service, "live-av");
        }
        return true;
    }

    public static boolean isVideoLockBell(DeviceItem deviceItem){
        return isLockBell(deviceItem) && isVideoLockBell(deviceItem.attrs);
    }

    public static boolean isSolar(DeviceItem deviceItem){
        return deviceItem != null && DeviceTypeHelper.isSolar(deviceItem.attrs);
    }


    public static boolean isPicLockBell(DeviceItem deviceItem){
        return isLockBell(deviceItem) && isPicLockBell(deviceItem.attrs);
    }

    public static boolean isNoMedia(DeviceItem deviceItem){
        if (deviceItem == null || StringUtils.isEmpty(deviceItem.abilities)){
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(deviceItem.abilities.toLowerCase());
        if (jsonObject != null){
            String key = jsonObject.getString("recordconf");
            return StringUtils.equalsIgnoreCase("no-media", key);
        }
        return false;
    }

    public static boolean isShowRecord(DeviceItem deviceItem, DeviceSettingsInfo deviceSettingsInfo){
        if (DeviceHelper.isSolar(deviceItem)){
            return true;
        }
        return isVoiceMan(deviceItem, deviceSettingsInfo);
    }

    public static boolean isVoiceMan(DeviceItem deviceItem, DeviceSettingsInfo deviceSettingsInfo){
        if (deviceItem != null && deviceSettingsInfo != null) {
            if (!StringUtils.isEmpty(deviceSettingsInfo.mode) && !StringUtils.isEmpty(deviceItem.firmware_id)) {
                return deviceSettingsInfo.mode.toLowerCase().contains("dsj") && deviceItem.firmware_id.toLowerCase().contains("Cenlux/Whycci".toLowerCase());
            }
            return false;
        }
        return false;
    }

    public static int getRotation(DeviceItem deviceItem){
        if (deviceItem == null || StringUtils.isEmpty(deviceItem.abilities)){
            return 0;
        }

        return DeviceFeature.getRotation(deviceItem.abilities);
    }

    public static AiSeviceInfo getSimServerData(DeviceItem deviceItem) {
        return deviceItem != null ? deviceItem.getSimServerData() : null;
    }

    public static boolean isCar(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.isCar();
    }

    public static boolean isLamp(DeviceItem deviceItem) {
        return false;
    }

    public static int getCustomerMessageCount(DeviceItem deviceItem) {
        if (deviceItem == null){
            return 0;
        }
        return deviceItem.getCustomerMessageCount();
    }

    public static boolean showCustomerServer(DeviceItem deviceItem){
        return deviceItem != null && deviceItem.isShowUnRead();
    }
    public static boolean isWifiDevice(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.isWifiDevice();
    }

    public static boolean isBatteryWifiDevice(DeviceItem deviceItem){
        return deviceItem != null && deviceItem.isBatteryWifiDevice();
    }

    public static boolean isSuportWechat(DeviceItem deviceItem){
        return deviceItem != null && deviceItem.isSuportWechat();
    }

    public static boolean isOnlyWifiDevice(DeviceItem deviceItem) {
        return deviceItem != null && DeviceTypeHelper.isOnlyWifiDevice(deviceItem.device_type);
    }

    public static boolean isCarWifiDevice(DeviceItem deviceItem) {
        return deviceItem != null && DeviceTypeHelper.isCarWifiDevice(deviceItem.device_type);
    }


    public static boolean isLanDevice(DeviceItem deviceItem) {
        return deviceItem != null && DeviceTypeHelper.isLanDevice(deviceItem.device_type);
    }

    public static boolean is4GDevice(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.is4GDevice();
    }

    public static boolean mustSleep(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.device_type != null && DeviceTypeHelper.hasSimCard(deviceItem.device_type)&&!isCar(deviceItem);
    }

    public static boolean is4GExpired(DeviceItem deviceItem) {
        return is4GExpired(deviceItem, false);
    }

    public static boolean is4GExpired(DeviceItem deviceItem, boolean neglectConnectWay) {
        return false;
//        if (neglectConnectWay){
//            return is4GDevice(deviceItem) && deviceItem.getSimServerData() == null && !DeviceHelper.isCar(deviceItem);
//        }
//        return is4GDevice(deviceItem) && deviceItem.getSimServerData() == null && TextUtils.equals(deviceItem.getConnectWay(), "sim") && !DeviceHelper.isCar(deviceItem);
    }


    public static boolean isCarExpired(DeviceItem deviceItem) {
        return isCar(deviceItem) && deviceItem.getCarServerData() == null;
    }

    public static boolean isGPSCar(DeviceItem deviceItem) {
        return isCar(deviceItem) && deviceItem.gps_model == 1;
    }

    public static boolean hasServe(DeviceItem deviceItem) {
        if (DeviceHelper.isLamp(deviceItem)){
            return DeviceHelper.hasLampServerProfessional(deviceItem);
        }

        if (DeviceHelper.isBirdFeeder(deviceItem)){
            return DeviceHelper.hasBirdFeederServer(deviceItem);
        }

        if (DeviceHelper.isLockBell(deviceItem) || DeviceHelper.isDoorBell(deviceItem)){
            return getServer(deviceItem) != null;
        }
        return isWifiDevice(deviceItem) && getServer(deviceItem) != null || isCar(deviceItem) && getCarServer(deviceItem) != null || is4GDevice(deviceItem) && !is4GExpired(deviceItem) && !DeviceHelper.isCar(deviceItem);
    }

    public static boolean isCarPrimary(DeviceItem deviceItem) {
        return isCar(deviceItem) && deviceItem.isCarPrimary();
    }

    public static boolean isAiCloud(DeviceItem mDevice){
        return is4GSupportCloud(mDevice)||(isCar(mDevice) && getCarServer(mDevice) != null);
    }
    public static boolean isStandard(DeviceItem deviceItem) {
        return isCar(deviceItem) && deviceItem.isStandard();
    }

    public static boolean hasLampServer(DeviceItem deviceItem){
       return deviceItem != null && deviceItem.isLamp() && deviceItem.ai_server_data != null;
    }

    public static boolean hasAiServer(DeviceItem deviceItem){
        return deviceItem != null && deviceItem.ai_server_data != null;
    }

    public static boolean hasBirdFeederServer(DeviceItem deviceItem){
        return isBirdFeeder(deviceItem) && deviceItem.ai_server_data != null;
    }

    public static boolean hasLampServerProfessional(DeviceItem deviceItem){
        return hasLampServer(deviceItem) && StringUtils.equalsIgnoreCase("2", deviceItem.ai_server_data.level);
    }

    public static boolean isProfessiona(DeviceItem deviceItem) {
        return isCar(deviceItem) && deviceItem.isProfessiona();
    }

    public static int getSaveDays(DeviceItem deviceItem) {
        if (isCar(deviceItem)) {
            CarServerData carServerData = getCarServer(deviceItem);
            return carServerData == null ? 0 : carServerData.save_days;
        }
        if (isWifiDevice(deviceItem)) {
            ServiceInfo serviceInfo = getServer(deviceItem);
            return serviceInfo == null ? 0 : serviceInfo.save_days;
        }

        if (is4GDevice(deviceItem)) {
            AiSeviceInfo aiSeviceInfo = getSimServerData(deviceItem);
            return aiSeviceInfo == null ? 0 : aiSeviceInfo.save_days;
        }

        return 0;
    }

    public static boolean isOff(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.is_open != DeviceStateConstants.DEVICE_OPEN;
    }

    public static boolean isOnline(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.is_online == DeviceStateConstants.DEVICE_ONLINE;
    }

    public static String getDeviceWifi(@NonNull DeviceItem deviceItem) {
        return ApScanConfiguration.INSTANCE.apNamePrefix() + "_" + deviceItem.uuid;
    }

    public static String getDeviceWifi(@NonNull String uuid) {
        if (!TextUtils.isEmpty(uuid) && uuid.startsWith(ApScanConfiguration.INSTANCE.apNamePrefix())) return uuid;
        return ApScanConfiguration.INSTANCE.apNamePrefix() + "_" + uuid;
    }

    public static boolean hasDeviceNotice(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.device_notice != null;
    }
    public static boolean isSetLockPWD(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.has_doorlock_pwd;
    }

    public static void onOpenServeFromClick(Context context, DeviceItem deviceItem){
        if (DeviceHelper.isCar(deviceItem)){
            ActivityHelper.openCarService(context, deviceItem);
        } else if (DeviceHelper.is4GDevice(deviceItem)){
            ActivityHelper.openWebService(context, deviceItem, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_SIM);
        } else if (DeviceHelper.isDoorBell(deviceItem) || DeviceHelper.isLockBell(deviceItem)){
            int type = CloudServiceActivity.EXT_DOORBELL_SERVICE_TYPE_STORAGEORCAR;
            if (DeviceHelper.isLockBell(deviceItem)){
                type = CloudServiceActivity.EXT_LOCKBELL_SERVICE_TYPE_STORAGEORCAR;
            }
            ActivityHelper.openWebService(context, deviceItem, type);
        } else if (DeviceHelper.isBirdFeeder(deviceItem)){
            ActivityHelper.openWebService(context, deviceItem, CloudServiceActivity.EXT_BIRD_FEEDER_SERVICE_TYPE_STORAGEORCAR);
        } else{
            ActivityHelper.openWebService(context, deviceItem, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_STORAGEORCAR);
        }
    }


    public static void openServe(DeviceItem deviceItem, Activity activity) {
        if (deviceItem != null && !StringUtils.isEmpty(deviceItem.foreignServiceHook)){
            AbAppUtil.openServeByBrowser(activity, deviceItem.foreignServiceHook);
        }else if (DeviceHelper.isLamp(deviceItem)){
            openStudyAssistantService(deviceItem, activity);
        } else if (DeviceHelper.isCar(deviceItem)) {
            String url = TGGlobalConfigHelper.getInstance().config().car_service_buy;
            if (StringUtils.isEmpty(url)){
                url = ApiUrl.CAR_BUY_PAGE;
            }
            UriUtil.openServePlay(activity, url, deviceItem == null ? 0 : deviceItem.id, 0, Activity.RESULT_FIRST_USER);

        } else if (DeviceHelper.is4GExpired(deviceItem)||DeviceHelper.is4GSupportCloud(deviceItem)) {
            UriUtil.openServePlay(activity, ApiUrl.SIM_BUY_PAGE, deviceItem == null ? 0 : deviceItem.id, 0, Activity.RESULT_FIRST_USER);

        } else {
            String url = TGGlobalConfigHelper.getInstance().config().storage_service_buy;
            if (DeviceHelper.is4GDevice(deviceItem)){
                url = TGGlobalConfigHelper.getInstance().config().sim_service_buy;
            }
            UriUtil.openServePlay(activity, url, deviceItem == null ? 0 : deviceItem.id, 0, Activity.RESULT_FIRST_USER);
        }
    }


    public static void openStudyAssistantService(DeviceItem deviceItem, Activity activity){
        if (deviceItem != null && !StringUtils.isEmpty(deviceItem.foreignServiceHook)){
            AbAppUtil.openServeByBrowser(activity, deviceItem.foreignServiceHook);
        }else{
            Intent intent = new Intent();
            DeviceSettingsInfo info = new DeviceSettingsInfo();
            info.deviceID = deviceItem.id;
            info.uuid = deviceItem.uuid;
            intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
            String url = TGGlobalConfigHelper.getInstance().getLearning_assistance_service();
            UriUtil.openServePlayImpl(activity, intent, url, "", 0);
        }
    }

    public static void openCustomerService(DeviceItem deviceItem, Activity activity){
        Intent intent = new Intent();
        DeviceSettingsInfo info = new DeviceSettingsInfo();
        info.deviceID = deviceItem.id;
        info.uuid = deviceItem.uuid;
        info.orderId = deviceItem.orderId;
        intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
        String url = deviceItem.orderUrl;

        UriUtil.openServePlayImpl(activity, intent, url, "", 0);

        AppLogManager.getInstance().uploadSilence("other-customer-service-entry");
    }



    public static boolean isDeviceForeignIccid(DeviceItem deviceItem) {
        return deviceItem != null && !TextUtils.isEmpty(deviceItem.foreign_iccid_notice) && (is4GDevice(deviceItem) || DeviceHelper.isCar(deviceItem));
    }

    public static boolean isShare(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.isShare();
    }
    public static boolean is4GSupportCloud(DeviceItem deviceItem){
        return deviceItem != null && is4GDevice(deviceItem)&&deviceItem.is_directional;
    }
    public static  boolean hasCloudeService(DeviceItem mDeviceItem){
            return DeviceHelper.hasServe(mDeviceItem) && (!DeviceHelper.is4GSupportCloud(mDeviceItem) || DeviceHelper.is4GHasCloud(mDeviceItem));

    }
    public static boolean is4GHasCloud(DeviceItem deviceItem){
        return deviceItem != null && is4GDevice(deviceItem)&&is4GSupportCloud(deviceItem)&&(deviceItem.getSimServerData()!=null&&deviceItem.getSimServerData().isSimCloud()||isCar(deviceItem)&&!isCarPrimary(deviceItem));
    }
    public static boolean isDoorBell(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.device_type != null && DeviceTypeHelper.isDoorBell(deviceItem.device_type);
    }

    public static boolean isLockBell(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.device_type != null && DeviceTypeHelper.isLockBell(deviceItem.device_type);
    }

    public static boolean isExistLockBellRelay(DeviceItem deviceItem){
        return isLockBell(deviceItem) && !StringUtils.isEmpty(deviceItem.tg_relay);
    }

    public static boolean isPassiveLockBell(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.device_type != null && DeviceTypeHelper.isPassiveLockBell(deviceItem.device_type);
    }

    public static boolean isPassiveDoorBellDevice(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.isPassiveDoorBellDevice();
    }

    public static boolean isPassiveDevice(DeviceItem deviceItem) {
        return isPassiveDoorBellDevice(deviceItem) || isPassiveLockBell(deviceItem);
    }

    public static boolean isLpLockBell(DeviceItem deviceItem) {
        return deviceItem != null && deviceItem.device_type != null && DeviceTypeHelper.isLpLockBell(deviceItem.device_type);
    }

    public static void openCameraDevice(Context context, int type, DeviceItem item) {
        TGThreadPool.executeOnUiThread(() -> {
            if (type == PUSH_TARGET_LIVE && DeviceHelper.isCar(item)) {
                TGToast.showToast(R.string.message_fail_no_car);
            } else {
                openDevice(context, item, type);
            }
        });
    }

    public static String getDeviceTypeName(@NonNull DeviceItem item){
        if (DeviceHelper.isLpWIFIBirdFeeder(item)){
            return ResourcesUtil.getString(R.string.device_type_lpwifibirdfeeder);
        }

        if (DeviceHelper.isWIFIBirdFeeder(item)){
            return ResourcesUtil.getString(R.string.device_type_wifibirdfeeder);
        }

        if (DeviceHelper.isSimBirdFeeder(item)){
            return ResourcesUtil.getString(R.string.device_type_simbirdfeeder);
        }

        if (DeviceHelper.isLockBell(item)) {
            return ResourcesUtil.getString(R.string.wifi_door_lock);
        }
        if (DeviceHelper.isDoorBell(item)){
            return ResourcesUtil.getString(R.string.txt_wifi_doorbell);
        }
        if (DeviceHelper.isLamp(item)){
            return ResourcesUtil.getString(R.string.txt_wifi_lamp);
        }

        if (DeviceHelper.isCar(item)) {
            if (DeviceTypeHelper.isBatteryDevice(item.device_type)) {
                return ResourcesUtil.getString(R.string.device_battery_car_4g);
            }
            return ResourcesUtil.getString(R.string.device_car_4g);
        }

        if (DeviceHelper.is4GDevice(item)) {
            if (DeviceTypeHelper.isBattery4GDevice(item.device_type)) {
                if (DeviceTypeHelper.isSolar(item.attrs)){
                    return ResourcesUtil.getString(R.string.device_solar);
                }
                return ResourcesUtil.getString(R.string.device_4g_battery);
            }
            return ResourcesUtil.getString(R.string.device_4g);
        }

        if (DeviceTypeHelper.isBatteryWifiDevice(item.device_type)) {
            if (DeviceTypeHelper.isSolar(item.attrs)){
                return ResourcesUtil.getString(R.string.wifi_device_solar);
            }
            return ResourcesUtil.getString(R.string.wifi_device_battery);
        }

        if (DeviceTypeHelper.isWifiDevice(item.device_type)){
            if (DeviceTypeHelper.isSolar(item.attrs)){
                return ResourcesUtil.getString(R.string.wifi_device_solar);
            }
            return ResourcesUtil.getString(R.string.device_wifi);
        }
        return ResourcesUtil.getString(R.string.camera);
    }



    public static void openDevice(Context context, DeviceItem device, int type) {
        Intent intent = new Intent();
        if (type == PUSH_TARGET_LIVE || type == OPEN_DRIVE_LOCAL_PALYBACK_SDCARD || type == OPEN_DRIVE_LOCAL || type == OPEN_DRIVE || type == FROM_CALL_PAGE_TARGET_LIVE) {
            if (TextUtils.equals("sim", device.connect_way) && TextUtils.equals("sim", device.device_type)) {
                // sim  4g卡连接，服务到期提示一次
                if (device.getSimServerData() == null) {
                    boolean isShow = PreferenceUtil.getBoolean(context, CommonConstants.PRE_SIM_SERVICE_NONE_PROPMPT + device.id);
                    if (!isShow) {
                        PreferenceUtil.setBoolean(context, CommonConstants.PRE_SIM_SERVICE_NONE_PROPMPT + device.id, true);
                        simServiceNone(context, device);
                        return;
                    }
                } else {
                    PreferenceUtil.setBoolean(context, CommonConstants.PRE_SIM_SERVICE_NONE_PROPMPT + device.id, false);
                }
            }
            if (type == OPEN_DRIVE_LOCAL && !TextUtils.isEmpty(device.uuid)) {
                String wifi = DeviceHelper.getDeviceWifi(device.uuid);
                WiFiScanManager.scanner().addCameraWifi(wifi, TGApplicationBase.getApplicationContext());
                intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, OPEN_DRIVE_LOCAL);
            } else {
                intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, PUSH_TARGET_LIVE);
            }
            TangeVideoPlayStatistics.resetStartTimeTotal();
            intent.putExtra(CommonConstants.EXT_DEVICE_ITEM, device);
            if (type == OPEN_DRIVE_LOCAL_PALYBACK_SDCARD){
                if (!StringUtils.isEmpty(device.attrs) && device.attrs.contains("2ch")){
                    intent.setClass(context, CameraPipPlaybackActivity.class);
                }else{
                    intent.setClass(context, CameraPlaybackActivity.class);
                }
            }else{
                if (!StringUtils.isEmpty(device.attrs) && device.attrs.contains("2ch")){
                    intent.setClass(context, CameraPipLiveActivity.class);
                }else{
                    intent.setClass(context, CameraLiveActivity.class);
                }

            }


            LogUtils.matTrackCustomKVEvent(context, "live_play", "LP");
        }  else if (type == OPEN_SETTING) {
            intent.setClass(context, DeviceSettingsActivity.class);
            intent.putExtra(CommonConstants.EXT_DEVICE_ITEM, device);
            intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, PUSH_TARGET_LIST);
        }

        int origin = intent.getIntExtra(CommonConstants.EXT_PUSH_ORIGIN, PUSH_TARGET_LIVE);
        TGLog.d(TAG, "orgin = " + origin);
        TGLog.d(TAG, "connect == ");
        intent.putExtra(CameraBaseActivity.FROM, P2PReport.DEVICE_LIST_PAGE);
        intent.putExtra(CommonConstants.EXT_DEVICE_ITEM, device);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void simServiceNone(Context context, final DeviceItem device) {
        new TGAlertDialog(context).builder().setMessage(ResourcesUtil.getString(R.string.sim_service_none))
                .setPositiveButton(R.string.sim_service_recharge, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (device != null && !StringUtils.isEmpty(device.foreignServiceHook)){
                            AbAppUtil.openServeByBrowser(context, device.foreignServiceHook);
                        }else{
                            Intent intent = new Intent();
                            DeviceSettingsInfo info = new DeviceSettingsInfo();
                            info.deviceID = device.id;
                            info.uuid = device.uuid;
                            intent.putExtra(EXT_DEVICE_INFO, info);
                            intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_SIM);
                            intent.setClass(context, CloudServiceActivity.class);
                            if (!(context instanceof Activity)) {
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }
                            context.startActivity(intent);
                        }

                    }
                }).setNegativeButton(ResourcesUtil.getString(R.string.sim_service_open_later), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    private static HashMap<String, String> getThirdDeviceListMap(String uuid) {
        HashMap<String, String> map = new HashMap<>();
        String appId = PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.THIRD_PARTY);
        map.put("appid", appId);
        map.put("uuid", uuid);
        map.put(DeviceListActivity.LIST_ATTR_PAGE, "1");
        map.put(DeviceListActivity.LIST_ATTR_LIMIT, "1");
        return map;
    }

    public static void queryBindState(String code, final TGDevice.TGDeviceListener listener) {

        DeviceMatchQuery.create().request(code, new DeviceMatchQuery.Callback() {
            @Override
            public void onSuccess(DeviceMatchBean deviceMatchBean) {
                String uuid = deviceMatchBean.getUuid();
                if (listener != null){
                    listener.onResult(true, 0, uuid);
                }
            }

            @Override
            public void onError(int errorCode, String errorMsg) {
                if (listener != null){
                    listener.onResult(false, errorCode, errorMsg);
                }
            }
        });
    }


    public static void getDevice(Context context, String uuid, final boolean openDevice, final TGDevice.TGDeviceListener listener) {
        HashMap<String, String> map = getThirdDeviceListMap(uuid);
        TGHttp.getInstance().getUserDeviceListDetail(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<UserDeviceListBean>() {
                    @Override
                    protected void onSuccess(UserDeviceListBean content) {
                        TGLog.i(TAG, "[getUserDeviceListDetail] onSuccess  + " + JSON.toJSONString(content));
                        List<DeviceItem> items = content.getItems();

                        if (items != null && items.size() > 0) {
                            TGLog.d(TAG, JSON.toJSONString(content));
                            DeviceItem deviceItem = items.get(0);
                            if (deviceItem != null && listener != null) {
                                listener.onResult(true, 0, "");
                                if (openDevice) {
                                    DeviceHelper.openCameraDevice(context, PUSH_TARGET_LIVE, deviceItem);
                                } else {
                                    ActivityHelper.goToMessageActivity(context, deviceItem);
                                }
                            }
                        } else if (listener != null) {
                            listener.onResult(false, TGErrorCode.ERROR_NO_FIND_DEVICE, "no find device");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (listener != null) {
                            listener.onResult(false, TGErrorCode.ERROR_LOCAL_OTHER, e.getMessage());
                        }
                    }

                    @Override
                    protected void onResponseError(int errorCode, String errorInfo) {
                        super.onResponseError(errorCode, errorInfo);
                        if (listener != null) {
                            listener.onResult(false, errorCode, errorInfo);
                        }
                    }

                    @Override
                    protected void onOtherError(String error) {
                        super.onOtherError(error);
                        if (listener != null) {
                            listener.onResult(false, TGErrorCode.ERROR_LOCAL_OTHER, error);
                        }
                    }
                });
    }


    public static void connectWifiDevice(Context context, String wifi, TGDevice.TGDeviceListener listener){
        if (listener != null){
            listener.onResult(true, 0, "");
        }
    }

    public static void openDevice(Context context, String uuid, final TGDevice.TGDeviceListener listener) {
        getDevice(context, uuid, true, listener);
    }

    public static Bitmap getQRCodeImageWifiDevice(String wifi, String pwd, int width, int height){
        String userId = String.valueOf(TGApplicationBase.getApplicationContext().getSharedPreferences(CommonConstants.PRE_SPNAME, MODE_PRIVATE).getInt(CommonConstants.PRE_USER_ID, -1));
        String content = DeviceWiFiConfiguration.createWiFiConfig(wifi, pwd, userId);
        Bitmap bitmap = DeviceWiFiConfiguration.createQrCode(content, width, height);
        return bitmap;
    }

    public static void addWifiDeviceByHotspot(Context context){
        ActivityHelper.goToWifiDeviceByHotspot(context);
    }

    public static void addWifiDeviceByQRCode(Context context){
        ActivityHelper.goToCodeWifiDeviceActivity(context, AddFragmentTabActivity.DEVICE_ADD_TYPE_QRCODE);
    }

    public static String getWifiDeviceQRString(String wifi, String pwd){
        String userId = String.valueOf(TGApplicationBase.getApplicationContext().getSharedPreferences(CommonConstants.PRE_SPNAME, MODE_PRIVATE).getInt(CommonConstants.PRE_USER_ID, -1));
        return DeviceWiFiConfiguration.createWiFiConfig(wifi, pwd, userId);
    }


    public static void add4gDevice(Context context, String uuid) {
        DeviceAddReportBean bean = DeviceAddReport.getInstance().getReportBean();
        if (bean != null) {
            bean.title = "4g_qrcode";
            DeviceAddReport.getInstance().setReportBean(bean);
        }

        Intent intent = new Intent(context, AddFragmentTabActivity.class);
        intent.putExtra(AddFragmentTabActivity.EXT_DEVICE_ADD_TYPE, AddFragmentTabActivity.DEVICE_ADD_TYPE_QRCODE_SCAN);
        intent.putExtra(AddFragmentTabActivity.EXT_DEVICE_ADD_UUID, uuid);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void showDeviceMessage(Context context, String uuid, final TGDevice.TGDeviceListener listener) {
        getDevice(context, uuid, false, listener);
    }
    public static boolean notPreconnect(DeviceItem deviceItem) {
        return deviceItem != null && !deviceItem.isPreconnect();
    }
    public static TimeZone getTimeZone(DeviceItem deviceItem){
        TimeZone mTimeZone;
        if (deviceItem != null && !TextUtils.isEmpty(deviceItem.timezone) && deviceItem.timezone.contains(",")) {
            String[] timezones = deviceItem.timezone.split(",");
            if (timezones.length > 1){
                mTimeZone = TimeZone.getTimeZone(timezones[1]);
            }else{
                mTimeZone = TimeZone.getDefault();
            }
        } else {
            mTimeZone = TimeZone.getDefault();
        }
        return mTimeZone;
    }



    public static void setSignalImage(DeviceItem deviceItem, TextView textView, int level){
        SignalHelper.setSignalImage(DeviceHelper.is4GDevice(deviceItem), textView, level);
    }

    public static void onServiceAiClick(Context context, DeviceItem item){
        if (DeviceItemHelper.isSuperAiService(item)){
            ActivityHelper.openWebService(context, item, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_SUPER_AI);
        }else{
            ActivityHelper.openWebService(context, item, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_AI);
        }
    }


    public static void setDeviceCardInfo(Context context, DeviceItem deviceItem, DeviceCardInfoView deviceCardInfoView){
        deviceCardInfoView.showFirstControl(true);
        deviceCardInfoView.showSecondControl(false);

        View.OnClickListener onFirstClick = v -> {
            if (deviceItem != null && !StringUtils.isEmpty(deviceItem.foreignServiceHook)){
                AbAppUtil.openServeByBrowser(context, deviceItem.foreignServiceHook);
            }else{
                DeviceHelper.onOpenServeFromClick(context, deviceItem);
            }
        };

        deviceCardInfoView.getView1().setOnClickListener(onFirstClick);
        deviceCardInfoView.getView2().setOnClickListener(onFirstClick);
        deviceCardInfoView.getTvFirst().setOnClickListener(onFirstClick);
        deviceCardInfoView.getIvFirst().setOnClickListener(onFirstClick);
        deviceCardInfoView.getLinearLayout().setOnClickListener(onFirstClick);

        if (DeviceHelper.isCar(deviceItem)) {
            deviceCardInfoView.setFirstText(R.string.settings_device_car);
            if (DeviceHelper.isCarExpired(deviceItem)){
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_car_expired_list);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.lock_door_status_close_color));
            }else{
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_car_list);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.message_body_textcolor));
            }
        }else if (DeviceHelper.is4GDevice(deviceItem)){
            if (DeviceHelper.is4GExpired(deviceItem, true)){
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_4g_expired_list);
                deviceCardInfoView.setFirstText(R.string.service_expired);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.sim_expired_color));
            }else{
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_4g_tryout_list);
                deviceCardInfoView.setFirstText(R.string.device_function_4g);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.message_body_textcolor));
            }
        }else if (DeviceHelper.isLamp(deviceItem)){
            deviceCardInfoView.setFirstText(R.string.txt_study_assistant_service);
            if (DeviceHelper.hasLampServer(deviceItem)){
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_learning_list);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.message_body_textcolor));
            }else{
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_learning_expired_list);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.lock_door_status_close_color));
            }
        } else if ((DeviceHelper.isLockBell(deviceItem) || DeviceHelper.isDoorBell(deviceItem) || DeviceHelper.isBirdFeeder(deviceItem))){
            deviceCardInfoView.setFirstText(R.string.txt_vip);

            if (DeviceHelper.hasBirdFeederServer(deviceItem) || getServer(deviceItem) != null){
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_premium_list);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.message_body_textcolor));
            }else{
                deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_premium_expired_list);
                deviceCardInfoView.setTextColor(ResourcesUtil.getResources().getColor(R.color.lock_door_status_close_color));
            }
        }else{
            deviceCardInfoView.showFirstControl(true);

            deviceCardInfoView.setFirstText(R.string.device_card_label_cloud_video);
            if (DeviceHelper.hasServe(deviceItem)){
               deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_cloud_list);
               deviceCardInfoView.setFirstTextColor(ResourcesUtil.getResources().getColor(R.color.message_body_textcolor));
            }else{
               deviceCardInfoView.setFirstImageIcon(R.drawable.ic_tange_global_icon_cloud_expired_list);
               deviceCardInfoView.setFirstTextColor(ResourcesUtil.getResources().getColor(R.color.lock_door_status_close_color));
            }

            if (LanguageUtils.isChinese(context)){
                deviceCardInfoView.setSecondText(R.string.device_server_ai);
            }else{
                deviceCardInfoView.setSecondText("AI");
            }

            if (SHOW_AI_SERVICE && (DeviceHelper.isOnlyWifiDevice(deviceItem) || DeviceHelper.isCarWifiDevice(deviceItem))) {
                deviceCardInfoView.showSecondControl(true);
                if (DeviceHelper.hasAiServer(deviceItem)){
                    deviceCardInfoView.setSecondImageIcon(R.drawable.ic_tange_global_icon_service_ai_tryout_list);
                    deviceCardInfoView.setSecondTextColor(ResourcesUtil.getResources().getColor(R.color.message_body_textcolor));
                }else{
                    deviceCardInfoView.setSecondImageIcon(R.drawable.ic_tange_global_icon_service_ai_expired_list);
                    deviceCardInfoView.setSecondTextColor(ResourcesUtil.getResources().getColor(R.color.lock_door_status_close_color));
                }
                deviceCardInfoView.getView2().setOnClickListener(v -> DeviceHelper.onServiceAiClick(context, deviceItem));
                deviceCardInfoView.getIvSecond().setOnClickListener(v -> DeviceHelper.onServiceAiClick(context, deviceItem));
                deviceCardInfoView.getTvSecond().setOnClickListener(v -> DeviceHelper.onServiceAiClick(context, deviceItem));
            }else{
                deviceCardInfoView.showSecondControl(false);
            }
        }
    }
}
